package com.frontop.system.modules.agora.controller;

import com.alibaba.fastjson.JSONObject;
import com.frontop.system.config.agora.media.RtcTokenBuilder;

import com.frontop.common.annotation.AnonymousAccess;
import com.frontop.common.util.ResultJsonUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 * 声网视频房间 前端控制器
 * </p>
 *
 * @author YangJia
 * @since 2022-06-29
 */
@RestController
@RequestMapping("/agora-room")
public class AgoraRoomController {
    static String appId = "bd5c696fc5194f8c8baa16cc48e8048d";
    static String appCertificate = "bd64259a3f8148bc9009ee8d081d036e";
    static int expirationTimeInSeconds = 3600;
    @ApiOperation(value = "声网视频进入房间")
    @GetMapping("/addRoom/{roomName}")
    @AnonymousAccess
    public ResultJsonUtil<Object> addRoom(@PathVariable("roomName") String roomName, Authentication authentication) {
        if(StringUtils.isNotBlank(roomName) && isOnlyLetterOrNumber(roomName)){
            RtcTokenBuilder token = new RtcTokenBuilder();
            int timestamp = (int)(System.currentTimeMillis() / 1000 + expirationTimeInSeconds);

            int uid =(int)(1+Math.random()*(9999-1+1));
            String result = token.buildTokenWithUid(appId, appCertificate,
                    roomName, uid, RtcTokenBuilder.Role.Role_Publisher, timestamp);
            System.out.println(result);
            JSONObject options = new JSONObject();
            options.put("appId",appId);
            options.put("channel",roomName);
            options.put("token",result);
            options.put("uid",uid);
            return new ResultJsonUtil().success(options);
        }else {
            return new ResultJsonUtil().customFail("非法房间名称");
        }
    }
    /**只允许用户输入数字字母a-z,A-Z,只能半角,不能有空格的正则表达式*/
    public static final String ONLY_LETTER_OR_NUMBER = "^[a-zA-Z]+$";
    public static boolean isOnlyLetterOrNumber(String str){
        return str.matches(ONLY_LETTER_OR_NUMBER);
    }


    // private static final long serialVersionUID = 1L;
    private static final String SERVICES_HOST = "www.webxml.com.cn";// 主机
    private static final String WEATHER_SERVICES_URL = "http://ws.webxml.com.cn/WebServices/WeatherWS.asmx/";
    // 获取天气																	getWeather?theCityCode=&theUserID=
    private static final String WEATHER_QUERY_URL = WEATHER_SERVICES_URL	+ "getWeather?theUserID=&theCityCode=";
    public static List<String> getWeathers(int cityCode) {
        //定义一个集合装载添加数据
        List<String> weatherList = new ArrayList<String>();
        /*获取xml文档对象*/
        Document document;
        /*获取解析工厂*/
        DocumentBuilderFactory documentBF = DocumentBuilderFactory.newInstance();
        //设定命名空间
        documentBF.setNamespaceAware(true);
        try {
            //初始xml工厂
            DocumentBuilder db = documentBF.newDocumentBuilder();
            //获取天气数据接口返回的数据
            URL urlObj = new URL(WEATHER_QUERY_URL+ cityCode);
            // 打开连接
            URLConnection urlConn = urlObj.openConnection();
            // 通过地址访问主机,设置请求代理
            urlConn.setRequestProperty("Host", SERVICES_HOST);
            //开始连接
            urlConn.connect();
            //读取
            InputStream inputStream = urlConn.getInputStream();
            //开始解析
            document = db.parse(inputStream);
            //解析string节点
            NodeList nl = document.getElementsByTagName("string");
            System.out.println(nl);
            int len = nl.getLength();
            for (int i = 0; i < len; i++) {
                Node n = nl.item(i);//获取每一个string节点
                //n.getFirstChild()获取文本节点
                String weather = n.getFirstChild().getNodeValue();
                weatherList.add(weather);
            }
            inputStream.close();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return weatherList;
    }


    public static void main(String[] args) {
        List<String> strings = AgoraRoomController.getWeathers(2350);
        System.out.println(strings);
    }
}
